package com.example.bodyguard;

import android.content.Context;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.Ringtone;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.io.IOException;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class MainActivity extends AppCompatActivity {
    private MAdapter mAdapter;
    private Context mContext;
    private RecyclerView rvLog;
    private Button stopBtn;
    private Button btnRemote;
    private ExecutorService pool;
    Ringtone ringtone;
    private boolean isAlarming;
    private ArrayList<PushBean> pushBeans;
    private String alarmPath = "file:///android_asset/alarm.mp3";

    private OkHttpClient client;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        EventBus.getDefault().register(this);
        mContext = this;
        pushBeans = new ArrayList<>();
        rvLog = findViewById(R.id.rv_log);

        stopBtn = findViewById(R.id.btn_stop);
        btnRemote = findViewById(R.id.btn_remote_alarm);

        stopBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                stopAlert();
                stopBtn.setVisibility(View.GONE);
            }
        });

        btnRemote.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                remoteAlert();
                btnRemote.setVisibility(View.GONE);
            }
        });

        mAdapter = new MAdapter();
        rvLog.setAdapter(mAdapter);

        LinearLayoutManager manager = new LinearLayoutManager(mContext);
        manager.setOrientation(RecyclerView.VERTICAL);
        rvLog.setLayoutManager(manager);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == R.id.action_settings) {
            pushBeans.clear();
            mAdapter.notifyDataSetChanged();
            stopBtn.setVisibility(View.GONE);
            btnRemote.setVisibility(View.GONE);
        }
        return super.onOptionsItemSelected(item);
    }

    private void remoteAlert() {
        RequestBody body = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), "{\"alarm\":\"true\"}");
        Request request = new Request.Builder()
                .url("http://10.2.140.188:8080/media/sendAlarm")
                .post(body)
                .build();

        if (client == null) {
            client = new OkHttpClient();
        }

        if (pool == null) {
            pool = Executors.newSingleThreadExecutor();
        }

        pool.execute(new Runnable() {
            @Override
            public void run() {
                Response execute = null;
                try {
                    execute = client.newCall(request).execute();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                Log.e("buxq", "execute: " + execute.toString());
            }
        });
    }


    @Subscribe
    public void onEvent(PushBean event) throws NoSuchFieldException, IllegalAccessException {
        Log.e("buxq", "onMessageEvent: " + event.toString());
        rvLog.post(new Runnable() {
            @Override
            public void run() {
                pushBeans.add(event);
                mAdapter.notifyDataSetChanged();
            }
        });
        //警报：
        alert();
    }

    private void alert() throws NoSuchFieldException, IllegalAccessException {
        if (isAlarming) {
            return;
        }
        isAlarming = true;

        stopBtn.post(new Runnable() {
            @Override
            public void run() {
                stopBtn.setVisibility(View.VISIBLE);
                btnRemote.setVisibility(View.VISIBLE);
            }
        });
        if (ringtone == null) {
            Uri uri = RingtoneManager
                    .getDefaultUri(RingtoneManager.TYPE_ALARM);
            ringtone = RingtoneManager.getRingtone(getApplicationContext(), uri);
            Class<Ringtone> clazz = Ringtone.class;
            Field field = clazz.getDeclaredField("mLocalPlayer");
            field.setAccessible(true);
            MediaPlayer target = (MediaPlayer) field.get(ringtone);
            target.setLooping(true);
            ringtone.setStreamType(AudioManager.STREAM_RING);
            Log.e("buxq", "alert path: " + uri.toString());
        }
        ringtone.play();
    }

    private void stopAlert() {
        if (ringtone != null) {
            try {
                ringtone.stop();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        isAlarming = false;
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    class MAdapter extends RecyclerView.Adapter<LogHolder> {

        public MAdapter() {

        }

        @NonNull
        @Override
        public LogHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_log, parent, false);
            LogHolder holder = new LogHolder(view);
            return holder;
        }

        @Override
        public void onBindViewHolder(@NonNull LogHolder holder, int position) {

            PushBean pb = pushBeans.get(position);

            String[] split = pb.time.split(" ");


            holder.tvYear.setText(split[0]);
            holder.tvHour.setText(split[1]);
            String typeMsg = "";
            switch (pb.type) {
                case "CAMERA":
                    typeMsg = "异常的光线变化";
                    break;
                case "MICROPHONE":
                    typeMsg = "异常声音";
                    break;
                case "ACCELEROMETER":
                    typeMsg = "手机被移动";
                    break;
                default:
                    break;
            }
            holder.tvLog.setText(typeMsg);
        }

        @Override
        public int getItemCount() {
            return pushBeans.size();
        }
    }

    static class LogHolder extends RecyclerView.ViewHolder {
        TextView tvLog;
        TextView tvYear;
        TextView tvHour;

        public LogHolder(View view) {
            super(view);
            tvLog = view.findViewById(R.id.tv_log);
            tvYear = view.findViewById(R.id.tv_year);
            tvHour = view.findViewById(R.id.tv_hour);
        }
    }
}
